package com.xk.demo.role.service.impl;

import com.xk.demo.mybatis.entity.PtDutyEntity;
import com.xk.demo.mybatis.entity.PtRoleEntity;
import com.xk.demo.mybatis.flexigrid.PadingRstType;
import com.xk.demo.mybatis.flexigrid.PagingBean;
import com.xk.demo.mybatis.ztree.ZtreeEntity;
import com.xk.demo.role.entity.SearchRoleEntity;
import com.xk.demo.role.respository.RoleDao;
import com.xk.demo.role.service.RoleService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;


    @Override
    public PadingRstType<PtRoleEntity> getRoleInfoListByPage(SearchRoleEntity search, PagingBean paging) {
        paging.deal(PtRoleEntity.class);
        PadingRstType<PtRoleEntity> padingRstType = new PadingRstType<>();
        padingRstType.setPage(paging.getPage());
        List<PtRoleEntity> list=roleDao.queryRoleListByPage(search,paging);
        Integer total=roleDao.queryRoleListTotal(search);
        padingRstType.setTotal(total);
        padingRstType.setRawRecords(list);
        padingRstType.putItems();

        return padingRstType;
    }

    @Override
    public List<ZtreeEntity> getMenuZtreeListByRoleId(String roleUuid) {
        Locale locale= LocaleContextHolder.getLocale();
        List<ZtreeEntity> list= roleDao.getMenuZtreeList(locale.toString());

        List<String> menuIdList=roleDao.getMenuZtreeListByRoleId(roleUuid);//之前的角色状态
        for (ZtreeEntity item:list){
            for(String menuId:menuIdList){
                if(menuId.equals(item.getId())){
                    item.setChecked(true);
                }
            }
        }

        return list;
    }

    @Override
    public void saveMenuByRoleId(String roleUuid, String menuIds) {
        String[] menuArray = menuIds.split(",");
        roleDao.deleteMenuByRole(roleUuid);
        roleDao.insertMenuRefRole(roleUuid,menuArray);

    }

    @Override
    public void insertRole(PtRoleEntity ptRoleEntity) {
        String uuid = UUID.randomUUID().toString(); //36
        uuid = uuid.replace("-",""); //32
        ptRoleEntity.setRoleUuid(uuid);
        ptRoleEntity.setRemarks("");
        roleDao.insertRole(ptRoleEntity);
    }

    @Override
    public int delRole(String uuid) {
        int flag;
        if((roleDao.searchUserInRole(uuid)==0)&&(roleDao.searchDutyByRole(uuid)==0))
            flag=0;
        else if((roleDao.searchUserInRole(uuid)!=0)&&(roleDao.searchDutyByRole(uuid)==0))
            flag=1;
        else if((roleDao.searchUserInRole(uuid)==0)&&(roleDao.searchDutyByRole(uuid)!=0))
            flag=2;
        else
            flag=3;
        if (flag==0)
        {
            roleDao.delRole(uuid);
            roleDao.delMenuByRole(uuid);
        }
        return flag;
    }




}
